package cn.hc.mq.general1;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * 同步生产者
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/9/19 9:20
 */
public class SyncProducer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        // 创建一个Producer，参数为Producer Group名称
        DefaultMQProducer producer = new DefaultMQProducer("pg");
        // 指定nameServer地址
        producer.setNamesrvAddr("rocketmqOS1:9876;rocketmqOS2:9876");
        // 设置重试次数，默认为2
        producer.setRetryTimesWhenSendFailed(3);
        // 设置消息发送超时时间为5s，默认为3秒
        producer.setSendMsgTimeout(5000);
        // 开启生产者
        producer.start();

        // 生产100条消息
        for (int i = 0; i < 100; i++) {
            byte[] body = ("Hi," + i).getBytes();
            Message msg = new Message("syncTopic", "someTag", body);
            msg.setKeys("key-" + i);
            // 发送消息
            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
        // 关闭生产者
        producer.shutdown();
    }
}
